/**
 * @Author Yenchingcheng
 * @Date 2023/5/15 0:07
 * @Description 双重检查
 **/
public class Singleton03 {

    public static void main(String[] args) {
        System.out.println("双重检查：");
        //测试Singleton4
        Singleton4 s1 = Singleton4.getInstance();
        Singleton4 s2 = Singleton4.getInstance();
        System.out.println(s1 == s2);//返回true
    }
}

//双重检查 (兼顾效率和懒加载)
class Singleton4 {
    //构造器私有化，不能new
    private Singleton4() {
    }

    //2.类内部创建静态对象实例,加volatile关键字
    private static volatile Singleton4 instance;

    //3.提供共有的静态方法，返回实例对象，加入双重检查代码，解决线程安全问题，同时解决懒加载问题
    public static Singleton4 getInstance() {
        //为空时才创建
        if (instance == null) {
            synchronized (Singleton4.class) {
                if (instance == null) {
                    instance = new Singleton4();
                }
            }
        }
        return instance;
    }
}
